# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 2019/4/30 13:59
desc: 中台功能
'''

import requests,random,logging,json
from datetime import datetime
from base.get_config import get_url_dict
from util.db_util import execute_query
import base.globalvars as glo
from proj_spec.knews.user import get_userid_by_email

class KnewsCore:
    def __init__(self):
        self.core_service = get_url_dict()['url3']
        self.es_service = get_url_dict()['url4'] #中间层
        self.tester_id = get_userid_by_email(glo.get_value("automation_tester"))

    def get_rule_settings(self,id):
        """获取事件设置"""
        res = execute_query("SELECT category_id,name_zh,source_type,emotion_type,company_list,industry_list,product_list,object_list,subscribe,subject_input FROM nlp_knews_user_rule WHERE id=%d"%id)
        return res

    def get_top_company(self,n=5):
        res = requests.get(self.es_service + "/knews/api/v1/es/rule/company/top").json()
        company = [item['name'] for item in res]
        return company[:n]

    def get_top_industry(self,n=5):
        if n>5:
            n=5
        industry=["通信设备","电脑与外围设备","电子制造","汽车","商业银行"]# 当前行业值写死，四级行业
        return industry[:n]

    def get_top_product(self,n=5):
        res = requests.get(self.es_service + "/knews/api/v1/es/rule/product/top").json()
        product = [item['name'] for item in res]
        return list(product[:n])

    def get_object_category(self,n=5):
        """获取客体分类"""
        result = execute_query("SELECT id,name_zh FROM nlp_dict_knews_object_category")
        return result[:n]

    def get_top_object_item(self,n=5):
        res = requests.get(self.es_service + "/knews/api/v1/es/rule/object/top").json()
        object = [item['name'] for item in res]
        return object[:n]

    def get_top(self,target,n=5):
        if target=='company':
            return self.get_top_company(n)
        elif target=='industry':
            return self.get_top_industry(n)
        elif target=='product':
            return self.get_top_product(n)
        elif target=='object':
            return self.get_top_object_item(n)

    def get_user_defined_object_item(self,n=5):
        if n>5:
            n=5
        object = ["现金流","复合增长率","股票","期权","配售"]
        return object[:n]

    def get_category_ids_of_user(self,userid):
        res = execute_query("SELECT id FROM nlp_knews_user_category WHERE create_user_id=%d"%userid)
        return [item[0] for item in list(res)]

    def get_core_sentence(self,rule_id,limit=15,offset=0):
        url = self.core_service + "/knews/core/v1/rule/%s/sentences?limit=%d&offset=%d" % (rule_id,limit,offset)
        headers = {"lang":"zh"}
        response = requests.get(url,headers=headers)
        return response

    def delete_category(self,category_id):
        pass

    def delete_rule(self,rule_id):
        res = requests.delete(self.core_service + "/knews/core/v1/rule/%d"%rule_id)
        pass

    def create_rule(self,subject,object,source_type,emotion):
        """根据各参数的各选项创建事件规则"""
        # 主体：1.公司 2.行业 3.产品 4.公司+行业+产品 5.用户自定义 6.多公司 7.多行业 8.多产品
        # 客体：1.事项 2.非事项 3.事项+非事项 4.空 5.用户自定义 Todo?6.多个事项 7.多个非事项
        # 信息源： 1.新闻 2.研报+公告 3.新闻+研报+公告
        # 情感：1,2,3,4

        # 输入主体
        companyList=industryList=productList=subjectInput=''

        n=5

        if subject==1 or subject==4:
            companyList=self.get_top_company(n)
            index = random.randint(0,n-1)
            companyList=companyList[index]
        if subject==2 or subject==4:
            industryList=self.get_top_industry(n)
            index = random.randint(0,n-1)
            industryList=industryList[index]
        if subject==3 or subject==4:
            productList=self.get_top_product(n)
            index = random.randint(0,n-1)
            productList=productList[index]
        elif subject==5:
            subjectInput=[self.get_top_company(n)[random.randint(0,n-1)]]
            subjectInput.append(self.get_top_industry(n)[random.randint(0,n-1)])
            subjectInput.append(self.get_top_product(n)[random.randint(0, n - 1)])
            subjectInput = ','.join(subjectInput)
        elif subject==6:
            companyList = random.sample(self.get_top_company(n),3)#随机取三个元素
            companyList = ','.join(companyList)
        elif subject==7:
            industryList = random.sample(self.get_top_industry(n),3)#随机取三个元素
            industryList = ','.join(industryList)
        elif subject==8:
            productList = random.sample(self.get_top_product(n),3)#随机取三个元素
            productList = ','.join(productList)

        # 输入客体
        objectList='[]'

        if object==1:
            object_category = self.get_object_category(n)[random.randint(0,n-1)]
            objectList = json.dumps([{"id":int(object_category[0]),"name":object_category[1]}],ensure_ascii=False)
        elif object==2:
            object_item = self.get_top_object_item(n)[random.randint(0,n-1)]
            objectList = json.dumps([{"id":-1,"name":object_item}],ensure_ascii=False)
        elif object==3:
            object_category = self.get_object_category(n)[random.randint(0,n-1)]
            objectList = [{'id':int(object_category[0]),'name':object_category[1]}]
            object_item = self.get_top_object_item(n)[random.randint(0,n-1)]
            objectList.append({'id':-1,'name':object_item})
            objectList = json.dumps(objectList,ensure_ascii=False)
            #objectList = repr(objectList)
        elif object==5:
            user_objectList = self.get_user_defined_object_item(n)
            objectList = []
            for obj in user_objectList:
                objectList.append({"id":-1,"name":obj})
            objectList = json.dumps(objectList,ensure_ascii=False)
            #objectList = repr(objectList)


        # 输入信息源
        if source_type==1:
            sourceType='1'
        elif source_type==2:
            sourceType='2,3'
        elif source_type==3:
            sourceType='1,2,3'


        # 输入情感
        emotionType = emotion

        categoryIds = self.get_category_ids_of_user(self.tester_id)
        categoryId = categoryIds[random.randint(0,len(categoryIds)-1)]
        time_str = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
        title = "automation_tester_%d_%d_%d_%d_%s"%(subject,object,source_type,emotion,time_str)
        subscribe=1

        headers = {"lang":"zh"}
        payload = {"categoryId":categoryId,
                   "title":title,
                   "sourceType":sourceType, #Todo
                   "emotionType":emotionType,
                   "subscribe":subscribe,
                   "companyList":companyList,
                   "industryList":industryList,
                   "productList":productList,
                   "objectList":objectList,
                   "subjectInput":subjectInput
                   }

        logging.debug("payload for rule:")
        logging.debug(json.dumps(payload,indent=4,ensure_ascii=False))
        res = requests.post(self.core_service+"/knews/core/v1/rule",data=payload,headers=headers).text

        #logging.debug(res)

        if res!='1':
            logging.error("事件规则创建失败")
            rule_id = 0
        else:
            # 获取rule id
            rule_id = execute_query("SELECT id FROM nlp_knews_user_rule WHERE name_zh='%s'"%title)[0][0]

        logging.debug(rule_id)
        return rule_id
